// src/utils/logger.rs

//! 日志配置和管理

use log::LevelFilter;
use env_logger::Builder;
use std::io::Write;

/// 日志配置
pub struct LoggerConfig {
    /// 日志级别
    pub level: LevelFilter,
    /// 是否输出到文件
    pub file_output: bool,
    /// 文件路径
    pub file_path: Option<String>,
    /// 是否使用彩色输出
    pub colored: bool,
    /// 时间戳格式
    pub timestamp_format: TimestampFormat,
}

/// 时间戳格式
#[derive(Debug, Clone)]
pub enum TimestampFormat {
    /// RFC3339
    Rfc3339,
    /// 简单格式
    Simple,
    /// ISO8601
    Iso8601,
}

impl Default for LoggerConfig {
    fn default() -> Self {
        Self {
            level: LevelFilter::Info,
            file_output: false,
            file_path: None,
            colored: true,
            timestamp_format: TimestampFormat::Rfc3339,
        }
    }
}

/// 日志管理器
pub struct LogManager {
    config: LoggerConfig,
}

impl LogManager {
    /// 创建新的日志管理器
    pub fn new(config: LoggerConfig) -> Self {
        Self { config }
    }

    /// 初始化日志系统
    pub fn init(&self) -> Result<(), Box<dyn std::error::Error>> {
        let mut builder = Builder::new();

        // 设置日志级别
        builder.filter_level(self.config.level);

        // 设置时间戳格式
        match self.config.timestamp_format {
            TimestampFormat::Rfc3339 => {
                builder.format_timestamp_secs();
            },
            TimestampFormat::Simple => {
                builder.format_timestamp_secs();
            },
            TimestampFormat::Iso8601 => {
                builder.format_timestamp_secs();
            },
        }

        // 设置文件输出
        if let Some(file_path) = &self.config.file_path {
            let file = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(file_path)?;

            builder.target(env_logger::Target::Pipe(Box::new(file)));
        }

        // 设置彩色输出
        if self.config.colored {
            builder.filter_module("industryagent", LevelFilter::Debug);
        }

        builder.init();

        Ok(())
    }

    /// 设置日志级别
    pub fn set_level(&mut self, level: LevelFilter) {
        self.config.level = level;
    }

    /// 获取当前配置
    pub fn config(&self) -> &LoggerConfig {
        &self.config
    }
}

/// 默认日志初始化
pub fn init_default_logger() -> Result<(), Box<dyn std::error::Error>> {
    let config = LoggerConfig::default();
    let logger = LogManager::new(config);
    logger.init()
}

/// 从环境变量初始化日志
pub fn init_logger_from_env() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = LoggerConfig::default();

    // 从环境变量读取日志级别
    if let Ok(level_str) = std::env::var("RUST_LOG") {
        config.level = match level_str.to_lowercase().as_str() {
            "error" => LevelFilter::Error,
            "warn" => LevelFilter::Warn,
            "info" => LevelFilter::Info,
            "debug" => LevelFilter::Debug,
            "trace" => LevelFilter::Trace,
            _ => LevelFilter::Info,
        };
    }

    // 从环境变量读取文件输出配置
    if std::env::var("LOG_FILE").is_ok() {
        config.file_output = true;
        config.file_path = std::env::var("LOG_FILE").ok();
    }

    // 从环境变量读取时间戳格式
    if let Ok(format_str) = std::env::var("LOG_TIMESTAMP_FORMAT") {
        config.timestamp_format = match format_str.to_lowercase().as_str() {
            "rfc3339" => TimestampFormat::Rfc3339,
            "simple" => TimestampFormat::Simple,
            "iso8601" => TimestampFormat::Iso8601,
            _ => TimestampFormat::Rfc3339,
        };
    }

    let logger = LogManager::new(config);
    logger.init()
}